package toutiao

import (
	"encoding/json"
	"fmt"
	"io"
	"math"
	"math/rand"
	"strconv"
	"time"

	"code.whyyou.me/yixiangguo/pub-platform/pub-lib/utils"
	"github.com/astaxie/beego"
	"github.com/kataras/go-errors"
)

type ToutiaoApi struct {
	mid int64
	username string
	ck string
}

func NewToutiaoApi(ck string,mid int64,username string) *ToutiaoApi {
	return &ToutiaoApi{
		ck: ck,
		mid:mid,
		username:username,
	}
}

func (t *ToutiaoApi) CheckCookie() error {
	req := utils.Get(`https://mp.toutiao.com/article/get_server_time/`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	res := CookieCheckRes{}
	if err :=req.ToJSON(&res); err != nil{
		return errors.New("cookie 失效")
	}

	return nil
}

func (t *ToutiaoApi) UploadImageByUrl(url string) (*UrlImageResponse, error) {
	req := utils.Post(`https://mp.toutiao.com/tools/catch_picture/?&`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	req.Param("upfile", url)

	urlImage := UrlImageResponse{}
	if err := req.ToJSON(&urlImage); err != nil {
		return nil, err
	}

	return &urlImage, nil
}

func (t *ToutiaoApi) GralleryUploadImageByFile(reader io.ReadCloser, filename string) (*FileImageResponse, error) {
	req := utils.Post(`https://mp.toutiao.com/tools/upload_picture/?type=ueditor&pgc_watermark=1&action=uploadimage&encode=utf-8`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("X_Requested_With", "X_Requested_With:XMLHttpRequest")

	req.PostFileByStream("upfile", filename, reader)

	fileImage := FileImageResponse{}
	if err := req.ToJSON(&fileImage); err != nil {
		return nil, err
	}
	return &fileImage, nil
}

func (t *ToutiaoApi) UploadImageByFile(reader io.ReadCloser, filename string, size int64) (*FileImageResponse, error) {
	req := utils.Post(`https://mp.toutiao.com/tools/upload_picture/?type=ueditor&pgc_watermark=1&action=uploadimage&encode=utf-8`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("X_Requested_With", "X_Requested_With:XMLHttpRequest")

	req.Param("id", "WU_FILE_0")
	req.Param("name", filename)
	req.Param("type", "image/png")
	req.Param("lastModifiedDate", time.Now().String())
	req.Param("size", strconv.FormatInt(size, 10))
	req.PostFileByStream("upfile", filename, reader)

	fileImage := FileImageResponse{}
	if err := req.ToJSON(&fileImage); err != nil {
		return nil, err
	}
	return &fileImage, nil
}

func (t *ToutiaoApi) publish(article TtArticle) (*PostArticleResponse, error) {
	req := utils.Post(`https://mp.toutiao.com/core/article/edit_article_post/?source=mp&type=article`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("X_Requested_With", "X_Requested_With:XMLHttpRequest")

	req.Param("article_type", "0")
	req.Param("title", article.Title)
	req.Param("content", article.Content)
	req.Param("claim_origin", "0")
	req.Param("article_ad_type", "3")
	req.Param("add_third_title", "0")
	req.Param("recommend_auto_analyse", "0")
	req.Param("tag", "0")
	req.Param("article_label", "")
	req.Param("is_fans_article", "0")
	req.Param("govern_forward", "0")
	req.Param("push_status", "0")
	req.Param("push_android_title", "")
	req.Param("push_android_summary", "")
	req.Param("push_ios_summary", "")
	req.Param("timer_status", "0")
	req.Param("timer_time", time.Now().Add(12*time.Hour).String())
	req.Param("column_chosen", "0")
	req.Param("pgc_id", "0")
	req.Param("is_app_preview", "1")

	imageCoversByte, err := json.Marshal(article.ImageCovers)
	if err != nil {
		return nil, err
	}
	fmt.Println(string(imageCoversByte))
	req.Param("pgc_feed_covers", string(imageCoversByte))
	req.Param("from_diagnosis", "0")
	req.Param("save", "1")

	postArticleResponse := PostArticleResponse{}
	if err := req.ToJSON(&postArticleResponse); err != nil {
		result, err := req.String()
		if err != nil {
			return nil, err
		}
		return nil, errors.New(result)
	}
	if postArticleResponse.Message != "提交成功"{
		return &postArticleResponse,errors.New(postArticleResponse.Message)
	}

	return &postArticleResponse, nil
}

func (t *ToutiaoApi) publishGallery(gallery TtGallery) (*PostArticleResponse, error) {
	req := utils.Post(`https://mp.toutiao.com/core/article/edit_article_post/?source=mp&type=figure`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("X_Requested_With", "XMLHttpRequest")

	req.Param("abstract", "")
	req.Param("authors", "")
	req.Param("self_appoint", "0")
	req.Param("save", "1")
	req.Param("pgc_id", "")
	req.Param("is_draft", "")

	req.Param("title", gallery.Title)
	req.Param("content", gallery.Content)
	req.Param("recommend_auto_analyse", "0")
	req.Param("article_ad_type", "2")
	req.Param("article_type", "3")
	req.Param("timer_status", "0")
	req.Param("timer_time", time.Now().Add(12*time.Hour).Format(`2006-01-02 15:04`))
	req.Param("from_diagnosis", "0")
	req.Param("pgc_debut", "0")

	for _, kv := range gallery.GalleryData {
		req.Param(kv.K, kv.V)
	}

	for _, kv := range gallery.GalleryInfo {
		req.Param(kv.K, kv.V)
	}

	postArticleResponse := PostArticleResponse{}
	if err := req.ToJSON(&postArticleResponse); err != nil {
		return nil, err
	}

	beego.Info("Content-Type:", req.GetRequest().Header.Get("Content-Type"))

	beego.Info("发表图集结果:", postArticleResponse.Message)

	return &postArticleResponse, nil
}

func getGalleryId() int64 {
	rand.Seed(time.Now().UnixNano())
	ts := float64(time.Now().UnixNano() / 1000000)
	rn := rand.Float64()
	return int64(math.Floor(ts * rn))
}

func (t *ToutiaoApi) uploadVideoMd5(md5 string) error {
	req := utils.Get(`https://mp.toutiao.com/video/video_uniq_api/?md5=` + md5)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	res := CommonResponse{}
	if err := req.ToJSON(&res); err != nil {
		return err
	}
	if res.Message != "success" {
		return errors.New("上传视频md5失败 :" + res.Message)
	}

	return nil
}

func (t *ToutiaoApi) getUploadApi() (UploadIdUrl, error) {
	req := utils.Post(`https://mp.toutiao.com/video/video_api/`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	req.Param("json_data", `{"api":"chunk_upload_info"}`)

	res := UploadApiResponse{}
	if err := req.ToJSON(&res); err != nil {
		bytes, _ := req.Bytes()
		beego.Error("上传API失败：", string(bytes))
		return UploadIdUrl{}, err
	}
	if res.Message != "success" {
		return UploadIdUrl{}, errors.New("获取上传视频API失败 :" + res.Message)
	}
	data := UploadIdUrl{}
	err := json.Unmarshal([]byte(res.Data), &data)
	if err != nil {
		return data, err
	}

	return data, nil
}

func (t *ToutiaoApi) preUploadVideo(uploadId string, log PreUploadLog) error {
	req := utils.Post(`https://i.snssdk.com/video/fedata/1/pgc/` + uploadId)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	logBytes, err := json.Marshal(log)
	if err != nil {
		return err
	}
	req.Param("log", string(logBytes))

	res := CommonResponse{}
	if err := req.ToJSON(&res); err != nil {
		return err
	}
	if res.Message != "success" {
		return errors.New("准备上传视频失败 :" + res.Message)
	}

	return nil
}

func (t *ToutiaoApi) uploadVideo(videoname string, args UploadIdUrl, reader io.ReadCloser) (UploadResponse, error) {
	req := utils.Post(args.UploadUrl)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	req.PostFileByStream("video_file", videoname, reader)

	res := UploadResponse{}
	err := req.ToJSON(&res)
	if err != nil {
		return res, err
	}

	if res.Message != "success" {
		return res, errors.New("上传视频失败 :" + res.Message)
	}

	return res, nil
}

func (t *ToutiaoApi) endUploadVideo(uploadId string, log EndUploadLog) error {
	req := utils.Post(`https://i.snssdk.com/video/fedata/1/pgc/` + uploadId)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	logBytes, err := json.Marshal(log)
	if err != nil {
		return err
	}
	req.Param("log", string(logBytes))

	res := CommonResponse{}
	if err := req.ToJSON(&res); err != nil {
		return err
	}
	if res.Message != "success" {
		return errors.New("准备上传视频失败 :" + res.Message)
	}

	return nil
}

func (t *ToutiaoApi) getVideoImage(vid string) (ImagesResponse, error) {
	req := utils.Get(fmt.Sprintf(`https://mp.toutiao.com/video/video_system_thumb/?vid=%s&item_id=`, vid))

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	res := ImagesResponse{}
	if err := req.ToJSON(&res); err != nil {
		return res, err
	}
	if res.Message != "success" {
		bytes, _ := req.Bytes()
		return res, errors.New("获取视频图片失败：" + string(bytes))
	}

	return res, nil
}

func (t *ToutiaoApi) reportVideoThumb(vid string, uri string) error {
	url := `https://mp.toutiao.com/video/video_thumb_report/?vid=%s&poster_uri=%s&poster_type=1`
	req := utils.Get(fmt.Sprintf(url, vid, uri))

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	res := CommonResponse{}
	if err := req.ToJSON(&res); err != nil {
		return err
	}
	if res.Message != "success" {
		return errors.New("确定视频封面失败 :" + res.Message)
	}

	return nil
}

func (t *ToutiaoApi) publishVideo(pub PubVideo) error {
	req := utils.Post(`https://mp.toutiao.com/core/article/edit_article_post/?source=mp&type=purevideo`)

	req.Header("Cookie", t.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	req.Param("article_ad_type", "2")
	req.Param("extern_link", "")
	req.Param("is_fans_article", "0")
	req.Param("add_third_title", "0")
	req.Param("timer_status", "0")
	req.Param("recommend_auto_analyse", "0")
	req.Param("from_diagnosis", "0")
	req.Param("praise", "0")
	req.Param("pgc_debut", "0")
	req.Param("save", "1")
	req.Param("article_type", "1")
	req.Param("timer_time", time.Now().Add(12*time.Hour).Format(`2006-01-02 15:04`))
	req.Param("article_label", pub.ArticleLabel)
	req.Param("content", pub.Content)
	req.Param("tag", pub.Tag)
	req.Param("abstract", pub.Desc)
	req.Param("title", pub.Title)

	res := PubVideoResponse{}

	err := req.ToJSON(&res)
	if err != nil {
		return err
	}

	if res.Message != "提交成功" {
		return errors.New("发表视频成功 :" + res.Message)
	}

	return nil
}
